package com.xinghai.system.service.impl;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xinghai.common.exception.ServiceException;
import com.xinghai.common.utils.DateUtils;

import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.QdOrder;
import com.xinghai.system.domain.QdStoreGood;
import com.xinghai.system.domain.QdUser;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.IQdOrderService;
import com.xinghai.system.service.IQdStoreGoodService;
import com.xinghai.system.service.IQdUserService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdStoreMapper;
import com.xinghai.system.domain.QdStore;
import com.xinghai.system.service.IQdStoreService;

/**
 * 店铺Service业务层处理
 *
 * @author xinghai
 * @date 2024-12-04
 */
@Service
public class QdStoreServiceImpl extends ServiceImpl<QdStoreMapper, QdStore>
        implements IQdStoreService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdStoreGoodService goodService;
    @Autowired
    private IQdOrderService orderService;
    /**
     * 查询店铺列表
     *
     * @param qdStore 店铺
     * @return 店铺集合
     */
    @Override
    public List<QdStore> list(QdStore qdStore) {
        QueryWrapper<QdStore> queryWrapper = new QueryWrapper<>();
        if (qdStore.getStatus()!= null  && !qdStore.getStatus().isEmpty()){
            queryWrapper.eq("status", qdStore.getStatus());
        }
        if (qdStore.getParams().get("beginCreateTime")!= null && !"".equals(qdStore.getParams().get("beginCreateTime"))
        &&qdStore.getParams().get("endCreateTime")!= null && !"".equals(qdStore.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdStore.getParams().get("beginCreateTime"),qdStore.getParams().get("endCreateTime"));
        }
        if (qdStore.getStoreName()!= null  && !qdStore.getStoreName().isEmpty()){
            queryWrapper.like("store_name", qdStore.getStoreName());
        }
        if (qdStore.getStoreLeader()!= null  && !qdStore.getStoreLeader().isEmpty()){
            queryWrapper.like("store_leader", qdStore.getStoreLeader());
        }
        if (qdStore.getStoreLeaderPhone()!= null  && !qdStore.getStoreLeaderPhone().isEmpty()){
            queryWrapper.like("store_leader_phone", qdStore.getStoreLeaderPhone());
        }
        if (qdStore.getWithdrawalStatus()!= null  && !qdStore.getWithdrawalStatus().isEmpty()){
            queryWrapper.eq("withdrawal_status", qdStore.getWithdrawalStatus());
        }
        if (qdStore.getNoPayDay()!= null  && !qdStore.getNoPayDay().isEmpty()){
            queryWrapper.eq("no_pay_day", qdStore.getNoPayDay());
        }
        if (qdStore.getGroupBuying()!= null  && !qdStore.getGroupBuying().isEmpty()){
            queryWrapper.eq("group_buying", qdStore.getGroupBuying());
        }
        if (qdStore.getParentStoreId()!= null){
            queryWrapper.eq("parent_store_id", qdStore.getParentStoreId());
        }
        return this.list(queryWrapper);
    }

    /**
     * 删除店铺信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdStore qdStore = new QdStore();
            qdStore.setId(id);
            qdStore.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdStore);
        }
        return this.removeById(id);
    }

    /**
     * 批量删除店铺信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdStore> collect = Arrays.stream(ids).map(m -> {
                QdStore qdStore = new QdStore();
                qdStore.setId(m);
                qdStore.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdStore;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入店铺信息
     *
     * @param list 店铺信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdStore> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdStoreMapper qdStoreMapper = sqlSession.getMapper(QdStoreMapper.class);
            list.forEach(qdStoreMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public QdStoreVo getIndexInfo(Long ascriptionStore) {
        QdStore store = getById(ascriptionStore);
        QdStoreVo dto = new QdStoreVo();
        BeanUtils.copyProperties(store, dto);
        dto.setReservationStartDateDay(DateUtils.getDate()+" "+store.getReservationStartDate());
        dto.setReservationEndDateDay(DateUtils.getDate()+" "+store.getReservationEndDate());
        dto.setSaleStartDateDay(DateUtils.getDate()+" "+store.getSaleStartDate());
        dto.setSaleEndDateDay(DateUtils.getDate()+" "+store.getSaleEndDate());
        return dto;
    }

    @Override
    @Transactional
    public boolean applyStore(QdStore child) {
        return saveInfo(child);
//        save(child);
//        QdUser user = new QdUser();
//        user.setId(child.getStoreLeaderId());
//        user.setAscriptionStore(child.getId());
//        user.setStoreLeader(child.getStoreLeader());
//        user.setStoreLeaderPhone(child.getStoreLeaderPhone());
//        user.setStoreName(child.getStoreName());
//        user.setStoreLeaderImg(child.getStoreLeaderImg());
//        user.setUserType("2");
//        user.setUpdateTime(new Date());
//        //userService.updateById(user);
//        //更新会员身份，店长 更换店铺信息
//        //TODO 申请开店，需不需要把店长的团队，全部迁移
//        return userService.updateById(user);
    }

    @Override
    @Transactional
    public boolean saveInfo(QdStore qdStore) {
        if (qdStore.getStoreLeaderId()==null){
            throw new ServiceException("请选择店长");
        }
        QdUser user = userService.getById(qdStore.getStoreLeaderId());
        if (user==null){
            throw new ServiceException("店长不存在");
        }
        if ("2".equals(user.getUserType())){
            throw new ServiceException("店长已存在店铺，请选择其他店长");
        }

        String s = userService.queryAllChild(String.valueOf(user.getId()));
        QueryWrapper<QdOrder> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.apply("FIND_IN_SET(seller_user_id,'"+s+"')");
        queryWrapper2.ne("status","3");
        queryWrapper2.ne("buyer_status","4");
        //queryWrapper2.and(q->q.eq("seller_status","1").or().apply("FIND_IN_SET(buyer_status,'1,2,3')"));
        List<QdOrder> list2 =orderService.list(queryWrapper2);
        List<QdOrder> orderList = list2.stream().filter(m -> "1".equals(m.getSellerStatus()) || "1".equals(m.getBuyerStatus()) || "2".equals(m.getBuyerStatus()) || "3".equals(m.getBuyerStatus())).collect(Collectors.toList());
        if (!orderList.isEmpty()){
            throw new ServiceException("该团队用户中有未完成订单，请先完成订单后再转单");
        }
        qdStore.setStoreLeader(user.getNickName());
        qdStore.setStoreLeaderPhone(user.getUserPhone());
        qdStore.setStoreLeaderImg(user.getAvatar());
        qdStore.setAppreciation(new BigDecimal("3.5"));
        qdStore.setListingFee(new BigDecimal("2"));
        qdStore.setPushFee(new BigDecimal("0.6"));
        qdStore.setMaxWithdrawalAmount(new BigDecimal(9999999));
        qdStore.setReservationStartDate("07:00:00");
        qdStore.setReservationEndDate("07:59:00");
        qdStore.setSaleStartDate("08:00:00");
        qdStore.setSaleEndDate("08:59:00");
        qdStore.setNoPayDay("星期天,星期六");
        qdStore.setWithdrawalRemark("1.统一提现时间每周五9：00-20：00;\n2.提现最小金额100，最大金额20000;\n3.提现到账时间T+1;");
        QdStoreGood storeGood = new QdStoreGood();
        if(StringUtils.isNotBlank(qdStore.getGroupOneName())){
            storeGood.setStoreId(qdStore.getId());
            storeGood.setGoodImg(qdStore.getGroupOneImage());
            storeGood.setGoodName(qdStore.getGroupOneName());
            storeGood.setGoodPrice(new BigDecimal(100));
            storeGood.setStatus("0");
            goodService.save(storeGood);
            qdStore.setGroupOneGoodId(storeGood.getId());
            qdStore.setGroupOneMinPrice(new BigDecimal(8001));
            qdStore.setGroupOneMaxPrice(new BigDecimal(20000));

            qdStore.setGroupTwoMinPrice(new BigDecimal(4001));
            qdStore.setGroupTwoMaxPrice(new BigDecimal(8000));
            qdStore.setGroupTwoGoodId(storeGood.getId());
            qdStore.setGroupTwoName(qdStore.getGroupOneName());
            qdStore.setGroupTwoImage(qdStore.getGroupOneImage());

            qdStore.setGroupThreeMinPrice(new BigDecimal(2000));
            qdStore.setGroupThreeMaxPrice(new BigDecimal(4000));
            qdStore.setGroupThreeGoodId(storeGood.getId());
            qdStore.setGroupThreeName(qdStore.getGroupOneName());
            qdStore.setGroupThreeImage(qdStore.getGroupOneImage());
        }

        save(qdStore);
        if(StringUtils.isNotBlank(qdStore.getGroupOneName())) {
            storeGood.setStoreId(qdStore.getId());
            storeGood.setStoreName(qdStore.getStoreName());
            storeGood.setStoreImg(qdStore.getStoreImg());
            storeGood.setStoreLeader(qdStore.getStoreLeader());
            storeGood.setStoreLeaderId(qdStore.getStoreLeaderId());
            storeGood.setStoreLeaderImg(qdStore.getStoreLeaderImg());
            storeGood.setStoreLeaderPhone(qdStore.getStoreLeaderPhone());
        }
        Long superId = user.getSuperId();
        user.setStoreName(qdStore.getStoreName());
        user.setAscriptionStore(qdStore.getId());
        user.setUserType("2");
        //user.setSuperId(null);
        //user.setSuperUserPhone("");
        user.setUpdateTime(new Date());
        user.setStoreLeader(user.getNickName());
        user.setStoreLeaderId(user.getId());
        user.setStoreLeaderPhone(user.getUserPhone());
        user.setStoreLeaderImg(user.getAvatar());

        //更新会员团队数据
        if (superId!=null){
            List<QdUser> allParentMemberById = userService.getAllParentMemberById(String.valueOf(superId));
            String s1 = allParentMemberById.stream().filter(m-> !Objects.equals(m.getId(), user.getId())).map(m -> String.valueOf(m.getId())).collect(Collectors.joining(","));
            userService.updateTeamNum(s1,-user.getTeamNum());
            userService.updatePushNum(String.valueOf(user.getSuperId()),-1);
        }
        //userService.updateById(user);
        userService.update(user, new UpdateWrapper<QdUser>()
                .lambda()
                .eq(QdUser::getId, user.getId())
                .set(QdUser::getSuperId, null)
                .set(QdUser::getSuperAvatar, null)
                .set(QdUser::getSuperUserName, null)
                .set(QdUser::getSuperUserPhone, null)
        );
        QdUser user1 = new QdUser();
        user1.setUserIds(s);
        List<QdUser> list = userService.list(user1);
        List<QdUser> userList = list.stream().filter(m-> !Objects.equals(m.getId(), user.getId())).map(m -> {
            QdUser qdUser = new QdUser();
            qdUser.setId(m.getId());
            qdUser.setAscriptionStore(qdStore.getId());
            qdUser.setStoreName(qdStore.getStoreName());
            qdUser.setUpdateTime(new Date());
            qdUser.setStoreLeader(user.getNickName());
            qdUser.setStoreLeaderId(user.getId());
            qdUser.setStoreLeaderPhone(user.getUserPhone());
            qdUser.setStoreLeaderImg(user.getAvatar());
            return qdUser;
        }).collect(Collectors.toList());
        if (!userList.isEmpty()){
            userService.updateBatchById(userList);
        }
        if(StringUtils.isNotBlank(qdStore.getGroupOneName())) {
            goodService.updateById(storeGood);
        }
        //更新订单为新店铺订单
        orderService.update(new UpdateWrapper<QdOrder>()
                .lambda()
                .set(QdOrder::getStoreId,qdStore.getId())
                .apply("FIND_IN_SET(seller_user_id,'"+s+"')")
                .ne(QdOrder::getStatus,"3")
                .ne(QdOrder::getBuyerStatus,"4")
                .eq(QdOrder::getSellerStatus,"0")
        );
        return true;
    }
}
